package com.hongshan.wallet.core.comm

import android.databinding.ViewDataBinding
import android.os.Bundle
import com.alibaba.android.arouter.facade.annotation.Route
import com.hongshan.wallet.Constant
import com.hongshan.wallet.MyApplication
import com.hongshan.wallet.R
import com.hongshan.wallet.base.MyActivity
import com.hongshan.wallet.base.MyViewModel
import com.hongshan.wallet.http.HttpClient
import com.hongshan.wallet.router.RouterIndex
import com.hongshan.wallet.router.go
import com.hongshan.wallet.toast
import com.hongshan.wallet.tryRun
import com.hongshan.wallet.util.MyActivityManager
import kotlinx.android.synthetic.main.activity_verification_pwd.*
import kotlinx.android.synthetic.main.appbar.*
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.async
import kotlinx.coroutines.launch

/**
 * Copyright Zhangxx.
 * Copyright (c) 2019
 * All rights reserved
 *
 * @project  : Wallet
 * @package  : com.example.wallet.core.comm
 * @author   : zhangxx
 * @date     : 2019/3/29
 * @email    : qq957413212@hotmail.com
 * @desc     : //TODO
 */
@Route(path = RouterIndex.VERIFICATION_PWD)
class VerificationPwdActivity : MyActivity<ViewDataBinding, MyViewModel>() {

    override fun initVariableId() = 0

    override fun initContentView(savedInstanceState: Bundle?) = R.layout.activity_verification_pwd

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        val title = intent.getStringExtra(Constant.ROUTE_PARAMS_KEY.VERFIFCATION_PWD_TITLE)
        if (title != null) {
            tvTitle.text = title
        }
        val buttonStr = intent.getStringExtra(Constant.ROUTE_PARAMS_KEY.VERFIFCATION_BUTTON)
        if (buttonStr != null) {
            tvComplete.text = buttonStr
        }
        val descStr = intent.getStringExtra(Constant.ROUTE_PARAMS_KEY.VERFIFCATION_PWD_DESC)
        val descAgainStr = intent.getStringExtra(Constant.ROUTE_PARAMS_KEY.VERFIFCATION_PWD_DESC_AGAIN)
        val needAgain = intent.getBooleanExtra(Constant.ROUTE_PARAMS_KEY.VERFIFCATION_PWD_NEED_AGAIN, false)
        val isAgain = intent.getBooleanExtra(Constant.ROUTE_PARAMS_KEY.VERFIFCATION_PWD_IS_AGAIN, false)

        if (needAgain){
            if (isAgain){
                tvDesc.text = descAgainStr
            } else{
                tvDesc.text = descStr
            }
        }

        tvComplete.setOnClickListener {
            val pwd = etPwd.text.trim().toString()
            if (!Constant.Regex.PAY_PWD.toRegex().matches(pwd)) {
                toast("密码格式错误")
                return@setOnClickListener
            }
            val newNeedAgain = intent.getBooleanExtra(Constant.ROUTE_PARAMS_KEY.VERFIFCATION_PWD_NEED_AGAIN, false)
            val newIsAgain = intent.getBooleanExtra(Constant.ROUTE_PARAMS_KEY.VERFIFCATION_PWD_IS_AGAIN, false)
            if (newNeedAgain && !newIsAgain) {
                if (intent.getStringExtra(Constant.ROUTE_PARAMS_KEY.VERFIFCATION_ACTION) == Constant.ROUTE_PARAMS_KEY.ACTION_SET_PAY_PWD) {
                    intent.putExtra(Constant.ROUTE_PARAMS_KEY.VERFIFCATION_PWD_FIRST_PWD, pwd)
                    intent.putExtra(Constant.ROUTE_PARAMS_KEY.VERFIFCATION_PWD_IS_AGAIN, true)
                    go(RouterIndex.VERIFICATION_PWD,intent.extras)
                    finish()
                }
            } else {
                val firstPwd = intent.getStringExtra(Constant.ROUTE_PARAMS_KEY.VERFIFCATION_PWD_FIRST_PWD)
                if (newNeedAgain && pwd != firstPwd) {
                    toast("两次输入密码不一致")
                    intent.putExtra(Constant.ROUTE_PARAMS_KEY.VERFIFCATION_PWD_IS_AGAIN, false)
                    return@setOnClickListener
                }
                val verifyCode = intent.getStringExtra(Constant.ROUTE_PARAMS_KEY.PAY_PWD_VERIFY_CODE)
                when (intent.getStringExtra(Constant.ROUTE_PARAMS_KEY.VERFIFCATION_ACTION)) {
                    Constant.ROUTE_PARAMS_KEY.ACTION_SET_PAY_PWD -> {
                        setPwd(pwd,verifyCode)
                    }
                    Constant.ROUTE_PARAMS_KEY.ACTION_CHECK_PAY_PWD -> {
                        checkPwd(pwd)
                    }
                }
            }
        }
    }

    fun setPwd(pwd:String,verifyCode:String) {
        GlobalScope.launch(Dispatchers.Main) {
            showLoading()
            val result = GlobalScope.async(Dispatchers.IO) {
                tryRun { HttpClient.httpApi.setPayPwd(verifyCode,pwd,pwd).execute() }
            }
            val response = result.await()
            showLoadSuccess()
            if (response?.body()?.code == 0) {
                toast("设置支付密码成功")
                val userDescBean = MyApplication.userInfo.get()
                userDescBean?.pay_password = "yes"
                MyApplication.userInfo.set(userDescBean)
                complete()
                MyActivityManager.getActivity(SendSmsActivity::class.java)?.finish()
            }else{
                toast(response?.body()?.msg)
            }
        }
    }

    fun checkPwd(pwd: String) {
        GlobalScope.launch(Dispatchers.Main) {
            showLoading()
            val result = GlobalScope.async(Dispatchers.IO) {
                tryRun { HttpClient.httpApi.checkPayPwd(pwd).execute() }
            }
            val body = result.await()?.body()
            showLoadSuccess()
            if (body?.code == 0){
                intent.putExtra(Constant.ROUTE_PARAMS_KEY.PAY_PWD_VERIFY_CODE,body.data.get("verify_code"))
                val path = intent.getStringExtra(Constant.ROUTE_PARAMS_KEY.VERFIFCATION_PWD_NEXT_URL)
                if (path != null) {
                    go(path, intent.extras)
                }
                val needFinish = intent.getBooleanExtra(Constant.ROUTE_PARAMS_KEY.VERFIFCATION_PWD_NEED_FINISH,false)
                if (needFinish){
                    finish()
                }
            }
        }
    }

    private fun complete() {
        val path = intent.getStringExtra(Constant.ROUTE_PARAMS_KEY.VERFIFCATION_PWD_NEXT_URL)
        val flag = intent.getIntExtra(Constant.ROUTE_PARAMS_KEY.ACTIVITY_FLAG,0)
        if (path != null) {
            go(path, intent.extras,flag = (if(flag == 0) null else flag))
        }
        if (intent.getBooleanExtra(Constant.ROUTE_PARAMS_KEY.VERFIFCATION_PWD_NEED_FINISH, false)) {
            finish()
        }
    }
}